/**
 * 
 */
package io.potato.core.util;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import lombok.extern.slf4j.Slf4j;

/**
 * xml bean相互转换
 * @author timl
 * created: 2019年1月09日 上午9:42:41
 */
@Slf4j
public class JaxbUtil {
	
	public static final String ENCODING = "GBK";
	
    /**
     * java对象转换为xml文件
     * @param xml  xml字符串
     * @param clazz    java对象.Class
     * @return    xml文件的String
     * @throws JAXBException    
     */
    public static String beanToXml(Object obj) {
        try {
        	JAXBContext context = getContext(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, ENCODING);
            //marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
            StringWriter writer = new StringWriter();
			marshaller.marshal(obj, writer);
			return writer.toString();
		} catch (JAXBException e) {
			log.error("jaxb error:" + e.getMessage());
		}
        return "";
    }

    /**
     * xml文件配置转换为对象
     * @param xml  xml字符串
     * @param clazz    java对象.Class
     * @return    java对象
     * @throws JAXBException    
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public static <T> T xmlToBean(String xml, Class<T> clazz) {
        try {
        	JAXBContext context = getContext(clazz);
            Unmarshaller unmarshaller = context.createUnmarshaller();
			return (T) unmarshaller.unmarshal(new StringReader(xml));
		} catch (JAXBException e) {
			log.error("jaxb error:" + e.getMessage());
		}
        return null;
    }
    
    static <T> JAXBContext getContext(Class<T> clazz) throws JAXBException {
    	return JaxbManager.instance().getContext(clazz);
    }
    
    public static void main(String[] args) {
    	
	}
    
    
	
	/**
	 * xml字符串转为java bean对象
	 * @param xml  xml字符串
	 * @param clazz  对象类型
	 * @return  java bean
	 */
	/*private static <T> T toBean(String xml, Class<T> clazz) {
		return JAXB.unmarshal(new StringReader(xml), clazz);
	}*/
	
	/**
	 * JAVA bean 对象转为xml字符串
	 * @param object  java bean对象
	 * @return  xml字符串
	 */
	/*private static String toXml(Object object) {
		StringWriter writer = new StringWriter();
		JAXB.marshal(object, writer);
		return writer.toString();
	}*/
}
